package com.example.mydownloader.mymodule.http

import android.text.TextUtils
import android.util.Base64
import com.example.mydownloader.config.globalConfig.UrlConfig
import com.example.mydownloader.myconst.TransmissionData
import com.example.mydownloader.mymodule.encrypt.AESKey
import com.example.mydownloader.mymodule.log.LogUtil
import com.example.mydownloader.mymodule.sharedpreferences.SPUtil
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * <Description> 拦截以json字符串形式传输数据的HTTP请求和响应，负责鉴权，加解密
 *
 * @author Wallace
 * @Date 2021/12/25 14:33
 */
object EncryptInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var eRequest = chain.request()
        if (needEncrypt(eRequest)) {
            val publicKeyString = SPUtil.getString(TransmissionData.RSA_PUBLIC_KEY)
            val securityKeyString = SPUtil.getString(TransmissionData.AES_KEY)
            val ivString = SPUtil.getString(TransmissionData.AES_IV)
            if (TextUtils.isEmpty(publicKeyString) ||
                TextUtils.isEmpty(securityKeyString) ||
                TextUtils.isEmpty(ivString)
            ) {
                // 终止请求
                throw NullPointerException("密钥丢失，无法加密，请求终止发送")
            } else {
                val publicKey = Base64.decode(publicKeyString.toByteArray(), Base64.NO_WRAP)
                val securityKey = Base64.decode(securityKeyString.toByteArray(), Base64.NO_WRAP)
                val iv = Base64.decode(ivString.toByteArray(), Base64.NO_WRAP)
                eRequest = encryptRequest(eRequest, AESKey(securityKey, iv), publicKey)
                LogUtil.d("encrypted request : ${eRequest.url}")
            }
        }
        var dResponse = chain.proceed(eRequest)
        if (needDecrypt(dResponse)) {
            val securityKeyString = SPUtil.getString(TransmissionData.AES_KEY)
            val ivString = SPUtil.getString(TransmissionData.AES_IV)
            if (TextUtils.isEmpty(securityKeyString) || TextUtils.isEmpty(ivString)) {
                // 终止处理
                throw NullPointerException("密钥丢失，无法解密")
            } else {
                val securityKey = Base64.decode(securityKeyString.toByteArray(), Base64.NO_WRAP)
                val iv = Base64.decode(ivString.toByteArray(), Base64.NO_WRAP)
                dResponse = decryptResponse(dResponse, AESKey(securityKey, iv))
                LogUtil.d("decrypt response : ${dResponse.request.url}")
            }
        }
//        LogUtil.d("ResponseBody = ${dResponse.body?.string() ?: "empty body"}")
        return dResponse
    }

    private fun needEncrypt(request: Request): Boolean {
        // GET和DELETE请求无body，无需加密
        if (request.method == "GET" || request.method == "DELETE") {
            return false
        }
        return true
    }

    private fun needDecrypt(response: Response): Boolean {
        // 预请求的返回无需解密
        if (response.request.url.toString() == UrlConfig.preRequestUrl) {
            return false
        }
        // 非正常状态不需要解密
        return response.isSuccessful
    }
}